<script lang="ts" setup>
import {
  ShoppingCart,
  Edit,
  Plus
} from '@element-plus/icons-vue';
import { ref, reactive } from 'vue'
import DefineComponent from "../utils/App";

DefineComponent();

// Token的Store
import { useTokenStore } from '@/store/token.js';
const tokenStore = useTokenStore();
// 关于商品的操作
import { GoodGetByPageService, GoodAddService } from '@/api/Goodinfo.js';
import { OrderAddService } from "@/api/order";
import { GoodShoppingAddService } from "@/api/shoppingcart";
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(5)//每页条数

// 获取用户的id
import { useUserInfoStore } from '@/store/user.js'
const userInfoStore = useUserInfoStore();

//获取上一次上传的图片的地址
import { imageStore } from '@/store/image.js'

const imageInfoStore = imageStore();

//  图片地址
const Image = ref(imageInfoStore.info)
console.log('图片地址：')
console.log(Image.value)
// 商品数据的模型
const Goodinfo = ref([
  {
    category: "2",
    price: 32.0,
    introduction: "aaa",
    status: 0,
    number: 32,
    username: "zhangqi",
    phone: "18698038688",
    gimage: "http",
    gname: "二手自用",
    gid: 1,
    statustype: '已通过',
    sid: 2,

  },
])

// imageInfoStore.info
// 上传商品时的数据模型
const GoodModel = ref({
  name: '',
  pId: userInfoStore.info.id,
  image: '',
  category: '',
  price: '',
  introduction: '',
  number: '',        // 数量

})

// 搜索模型
const formInline = reactive({
  name: '',
  category: '',
})

//  清空搜索栏
const clear = () => {
  formInline.name = '',
    formInline.category = ''
}

// 条件分页查询
const GoodList = async () => {
  let params = {
    page: pageNum.value,
    pageSize: pageSize.value,
    name: formInline.name ? formInline.name : null,
    category: formInline.category ? formInline.category : null
  }

  let result = await GoodGetByPageService(params);

  console.log("返回结果:" + result)
  console.log(result)

  //渲染列表数据
  Goodinfo.value = result.data.rows
  //渲染总条数
  total.value = result.data.total
  //  修改属性名字   管理员页面需要
  //为列表中添加categoryName属性
  for (let i = 0; i < Goodinfo.value.length; i++) {
    let info = Goodinfo.value[i];
    for (let j = 0; j < Goodinfo.value.length; j++) {
      if (info.status === 0) {
        info.statustype = '待审核'
      } else if (info.status === 1) {
        info.statustype = '已通过'
      } else {
        info.statustype = '已下架'
      }
    }
  }
}

GoodList()

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  GoodList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  GoodList()
}



import { ElMessage } from 'element-plus'

// 添加商品
const dialogAddVisible = ref(false)

const GoodAdd = async () => {

  console.log('数据：' + GoodModel.value)
  var result = await GoodAddService(GoodModel.value)

  // 这里查看res的结果时，要使用async，await，才能访问res
  console.log(result.code)
  // 成功
  if (result.code === 1) {
    ElMessage.success(result.msg ? result.msg : '添加成功')
    console.log(result)
    dialogAddVisible.value = false
  } else {
    ElMessage.error('添加失败')
  }
  imageInfoStore.removeInfo()
}

const acphoto = () => {
  var newimageInfoStore = imageStore();

  //  图片地址
  Image.value = newimageInfoStore.info

  GoodModel.value.image = newimageInfoStore.info

}
//  添加订单
const addorder = async (row) => {

  let params = {
    gId: row.gid,
    number: 1,
    totalPrice: row.price,
    sId: row.sid        // 卖家id
  }

  let result = await OrderAddService(params)

  // 成功
  if (result.code === 1) {
    ElMessage.success(result.msg ? result.msg : '添加成功')

  } else {
    ElMessage.error('添加失败')
  }
  GoodList()
}

// 添加购物车
const shopping = async (row) => {

  let params = {
    gId: row.gid,
    number: 1,
    totalPrice: row.price,
    bid: userInfoStore.info.id,
    sId: row.sid        // 卖家id
  }

  let result = await GoodShoppingAddService(params)

  // 成功
  if (result.code === 1) {
    ElMessage.success(result.msg ? result.msg : '添加成功')

  } else {
    ElMessage.error('添加失败')
  }
  GoodList()
}

//  上传成功的回调      
const uploadSuccess = (result) => {
  GoodModel.value.image = result.data
  console.log(result.data);

}
</script>


<template>
  <el-card class="">
    <div class="card-header">
      <span>商品管理</span>
      <el-button type="primary" @click="acphoto; dialogAddVisible = true">发布商品</el-button>
    </div>
    <div style="margin-top: 20px;">
      <hr>
    </div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="商品名称:">
        <el-input v-model="formInline.name" placeholder="商品名称" clearable />
      </el-form-item>

      <el-form-item label="商品类型：">
        <el-input v-model="formInline.category" placeholder="商品类型" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="GoodList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="default" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="Goodinfo" style="width: 100%">
      <el-table-column type="expand">
        <template #default="props">
          <div m="4">
            <p m="t-0 b-2">商品编号: {{ props.row.gid }}</p>
            <p m="t-0 b-2">商品简介: {{ props.row.introduction }}</p>
            <!-- <p m="t-0 b-2">商品状态: {{ props.row.status }}</p>  -->
            <p m="t-0 b-2">商品库存: {{ props.row.number }}</p>
            <p m="t-0 b-2">卖家: {{ props.row.username }}</p>
            <p m="t-0 b-2">卖家联系电话: {{ props.row.phone }}</p>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="商品名称" prop="gname" />

      <el-table-column label="图像" prop="gimage">
        <template #default="{ row }">
          <img :src=row.gimage alt="图片走丢了" style="height: 100px" />
        </template>
      </el-table-column>

      <el-table-column label="商品类别" prop="category" />
      <el-table-column label="价格" prop="price" />
      <el-table-column label="商品状态" prop="statustype" />

      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" :icon="ShoppingCart" circle @click="shopping(row)" />
          <el-button type="primary" round @click="addorder(row)">加入订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
      @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  </el-card>

  <!-- // 上传商品 -->
  <el-dialog v-model="dialogAddVisible" title="添加商品" width="30%">
    <el-form :model="GoodModel" label-width="100px" style="padding-right: 30px">
      <!-- <el-form-item label="商品编号" prop="id">
          <el-input v-model="GoodModel.id" minlength="1" maxlength="10" disabled></el-input>
        </el-form-item> -->
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="GoodModel.name" minlength="1" maxlength="15"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" prop="image">
        <el-upload class="goodimg-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload" name="image"
          :headers="{ 'token': tokenStore.token.token }" :on-success="uploadSuccess">
          <img v-if="GoodModel.image" :src=GoodModel.image alt="图片走丢了" class="goodimg" title="点击图片可以修改图像"/>
          <el-icon v-else class="goodimg-uploader-icon" title="点击图片可以修改图像">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品类别" prop="category">
        <el-input v-model="GoodModel.category" minlength="1" maxlength="15"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="GoodModel.price" minlength="1" maxlength="15"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="introduction">
        <el-input v-model="GoodModel.introduction" minlength="1" maxlength="15"></el-input>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
          <el-input v-model="GoodModel.status" minlength="1" maxlength="15" disabled></el-input>
        </el-form-item> -->
      <el-form-item label="库存" prop="number">
        <el-input v-model="GoodModel.number" minlength="1" maxlength="15"></el-input>
      </el-form-item>
      <el-form-item label="用户id" prop="pId">
        <el-input v-model="GoodModel.pId" minlength="1" maxlength="15" disabled></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取消</el-button>
        <el-button type="primary" @click="GoodAdd"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>


<style scoped>
.el-p {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-input {
  width: 220px;
}

.el-select {
  width: 220px;
}


.card-header {
  display: flex;
  justify-content: space-between;
}

.goodimg-uploader {
  
    .goodimg {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.goodimg-uploader-icon {
      font-size: 28px;
      color: #242527;
      width: 150px;
      height: 150px;
      text-align: center;
      background-color: #7779733e;
    }
  
}

</style>